import os
import subprocess
import time

from flask import current_app

from config import BASE_DIR, NGINX_RTMP


class VideoStream(object):
    def __init__(self, key1, key2, key3):
        # s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        # s.connect(('8.8.8.8', 80))
        # self.ip = s.getsockname()[0]
        # current_app.logger.info('服务器 %s', self.ip)
        self.key1 = None if key1 == 'None' else key1
        self.key2 = None if key2 == 'None' else key2
        self.key3 = None if key3 == 'None' else key3

    def check_file(self, models):
        filters = {'key1': self.key1, 'key2': self.key2, 'key3': self.key3}
        file_key = models.FileKey.query.filter_by(**filters).one_or_none()
        if file_key is None:
            return False, '视频不唯一或者不存在'
        upload_file_id = file_key.ufid
        current_app.logger.info('upload_file id为%s', upload_file_id)
        upload_file = models.UploadFile.query.filter_by(id=upload_file_id).one_or_none()
        if file_key is None:
            return False, '数据库内存储的视频错误', ''
        path = upload_file.filepath
        current_app.logger.info('推流视频文件地址 %s', path)
        # if not os.path.exists(path):
        #     current_app.logger.info('用于推送的缓存视频文件不存在，开始从数据库提取')
        #     make_dir(UPLOAD_FOLDER)
        #     file = open(path, 'wb')
        #     file.write(upload_file.filecontext)
        return True, path

    def check_download_file(self, models):
        filters = {'key1': self.key1, 'key2': self.key2, 'key3': self.key3}
        file_key = models.FileKey.query.filter_by(**filters).one_or_none()
        if file_key is None:
            return False, '视频不唯一或者不存在'
        upload_file_id = file_key.ufid
        current_app.logger.info('upload_file id为%s', upload_file_id)
        upload_file = models.UploadFile.query.filter_by(id=upload_file_id).one_or_none()
        if file_key is None:
            return False, '数据库内存储的视频错误'
        path = upload_file.filepath
        current_app.logger.info('下载视频文件地址 %s', path)
        # if not os.path.exists(path):
        #     current_app.logger.info('用于下载的缓存视频文件不存在，开始从数据库提取')
        #     make_dir(UPLOAD_FOLDER)
        #     file = open(path, 'wb')
        #     file.write(upload_file.filecontext)
        return True, path, file_key.filename

    def get_url(self, path):
        fix = str(time.time()).replace(".", "")
        url = 'rtmp://' + NGINX_RTMP + ':1935/live/' + fix
        ffmpegpath = BASE_DIR + os.sep + 'ffmpeg' + os.sep + 'ffmpeg'
        command = [ffmpegpath,
                   '-i', path,
                   '-r', '16',
                   '-vcodec', 'h264',
                   '-acodec', 'aac',
                   '-f', 'flv',
                   url]
        pip = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
        # pip = subprocess.Popen(command)
        current_app.logger.info('直播视频流地址 %s', url)
        return url
